import Vue from 'vue'
import axios from 'axios'
import store from '@/store'
import { VueAxios } from './axios'
import {Modal, notification} from 'ant-design-vue'
import { ACCESS_TOKEN, USER_INFO } from "@/store/mutation-types"
import BASE_URL from '../../config'

//自动设置后台服务 baseURL (也可以手工指定写死项目名字)
let baseDomain = window._CONFIG['domianURL'];
let baseProject = baseDomain.substring(baseDomain.lastIndexOf("/"));
// console.log("baseDomain= ",baseDomain)
// console.log("baseProject= ",baseProject)

// 创建 axios 实例
const service = axios.create({
  baseURL: BASE_URL,
  // baseURL: 'http://47.110.124.233:13301/jeecg-boot', // api base_url
  timeout: 9000 // 请求超时时间
})

//  用户登录信息是否过期
const err = (error) => {
  if (error.response) {
    let data = error.response.data
    // const token = Vue.ls.get(ACCESS_TOKEN)
    console.log("------异常响应------",token)
    console.log("------异常响应------",error.response.status)
    switch (error.response.status) {
      case 403:
        notification.error({ message: '系统提示', description: '拒绝访问',duration: 4})
        break
      case 500:
        console.log("------error.response------",error.response)
        // update-begin- --- author:liusq ------ date:20200910 ---- for:处理Blob情况----
        let type=error.response.request.responseType;
        if(type === 'blob'){
          blobToJson(data);
          break;
        }
        // update-end- --- author:liusq ------ date:20200910 ---- for:处理Blob情况----
        //notification.error({ message: '系统提示', description:'Token失效，请重新登录!',duration: 4})
        if(token && data.message=="Token失效，请重新登录"){
          // update-begin- --- author:scott ------ date:20190225 ---- for:Token失效采用弹框模式，不直接跳转----
          // store.dispatch('Logout').then(() => {
          //     window.location.reload()
          // })
          Modal.error({
            title: '登录已过期',
            content: '很抱歉，登录已过期，请重新登录',
            okText: '重新登录',
            mask: false,
            onOk: () => {
              Vue.ls.remove(ACCESS_TOKEN)
              Vue.ls.remove(USER_INFO)
              window.location.href="/"
              // window.location.reload()
              // store.dispatch('Logout').then(() => {
              //   Vue.ls.remove(ACCESS_TOKEN)
              //   try {
              //     let path = window.document.location.pathname
              //     console.log("location pathname -> "+path)
              //     if(path!="/" && path.indexOf('/user/login')==-1){
              //       window.location.reload()
              //     }
              //   }catch (e) {
              //     window.location.reload()
              //   }
              // })
            }
          })
          // update-end- --- author:scott ------ date:20190225 ---- for:Token失效采用弹框模式，不直接跳转----
        }
        break
      case 404:
        // 暂时注释
          // notification.error({ message: '系统提示', description:'很抱歉，资源未找到!',duration: 4})
        break
      case 504:
        notification.error({ message: '系统提示', description: '网络超时'})
        break
      case 401:
        notification.error({ message: '系统提示', description:'未授权，请重新登录',duration: 4})
        if (token) {
          // store.dispatch('Logout').then(() => {
          //   setTimeout(() => {
          //     window.location.reload()
          //   }, 1500)
          // })
            Vue.ls.remove(ACCESS_TOKEN)
            Vue.ls.remove(USER_INFO)
            window.location.href="/"
            // window.location.reload()
        }
        break
      default:
        notification.error({
          message: '系统提示',
          description: data.message,
          duration: 4
        })
        break
    }
  }
  return Promise.reject(error)
};

// request interceptor
service.interceptors.request.use(config => {
  const token = Vue.ls.get(ACCESS_TOKEN)
  if (token) {
    config.headers[ 'token' ] = token // 让每个请求携带自定义 token 请根据实际情况自行修改
  }
  if(config.method=='get'){
    if(config.url.indexOf("sys/dict/getDictItems")<0){
      config.params = {
        _t: Date.parse(new Date())/1000,
        ...config.params
      }
    }
  }
  return config
},(error) => {
  return Promise.reject(error)
})

// response interceptor
service.interceptors.response.use((response) => {
  if(response.data.code == 0) {
    return response.data
  } else if (response.data.code == 401) {
    Modal.error({
      title: '系统提示',
      content: '未授权，请重新登录',
      okText: '重新登录',
      mask: false,
      onOk: () => {
        Vue.ls.remove(ACCESS_TOKEN)
        Vue.ls.remove(USER_INFO)
        window.location = "/"
        // window.location.reload()
      }
    })
  } else {
    return response.data
  }
    
  }, err)

const installer = {
  vm: {},
  install (Vue, router = {}) {
    Vue.use(VueAxios, router, service)
  }
}

function blobToJson(data) {
  let fileReader = new FileReader();
  let token = Vue.ls.get(ACCESS_TOKEN);
  fileReader.onload = function() {
    try {
      let jsonData = JSON.parse(this.result);  // 说明是普通对象数据，后台转换失败
      console.log("jsonData",jsonData)
      if (jsonData.status === 500) {
        console.log("token----------》",token)
        if(token && jsonData.message.includes("Token失效")){
          Modal.error({
            title: '登录已过期',
            content: '很抱歉，登录已过期，请重新登录',
            okText: '重新登录',
            mask: false,
            onOk: () => {
              // store.dispatch('Logout').then(() => {
              //   Vue.ls.remove(ACCESS_TOKEN)
              //   window.location.reload()
              // })
              Vue.ls.remove(ACCESS_TOKEN)
              Vue.ls.remove(USER_INFO)
              window.location.href="/"
              // window.location.reload()
            }
          })
        }
      }
    } catch (err) {
      // 解析成对象失败，说明是正常的文件流
      console.log("blob解析fileReader返回err",err)
    }
  };
  fileReader.readAsText(data)
}

export {
  installer as VueAxios,
  service as axios
}